package com.soft.base.log;

import ch.qos.logback.classic.spi.LoggingEvent;
import ch.qos.logback.core.UnsynchronizedAppenderBase;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.soft.base.util.HttpUtil;
import com.soft.base.util.HttpUtil;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;
/**
 * class
 *
 * @author user
 * @date 2020/06/05
 */
@Slf4j
public class LogReportAppender<E> extends UnsynchronizedAppenderBase<E> {

    @Setter
    @Getter
    private String url;

    @Getter
    @Setter
    private String app;

    @Override
    protected void append(E eventObject) {
        if (!(eventObject instanceof LoggingEvent)) {
            return;
        }
        if (null == url || url.length() == 0) {
            return;
        }
        LoggingEvent event = (LoggingEvent) eventObject;

        JSONObject report = new JSONObject();
        StackTraceElement[] caller = event.getCallerData();
        String node = "unknown";
        try {
            node = InetAddress.getLocalHost().getHostName();
        } catch (UnknownHostException e) {
        }
        report
                .fluentPut("node", node)
                .fluentPut("app", app)
                .fluentPut("time", event.getTimeStamp())
                .fluentPut("level", event.getLevel().toString())
                .fluentPut("thread", event.getThreadName())
                .fluentPut("msg", event.getFormattedMessage());
        if (caller != null && caller.length > 0) {
            report.fluentPut("location", caller[0].toString());
        }

        Map<String, Object> param = new HashMap<String, Object>(128);
        param.put("data", JSON.toJSONString(report));
        try {
            HttpUtil.get(url, null, param);
        } catch (Exception e) {
            log.error("LogReportAppender.error", e);
        }

    }
}
